/**
 * 
 */

package type;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.e885.log.E885Logger;
import common.MyBean;

/**
 * @author Eric.Kao(gau168.gau@msa.hinet.net)
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2001-2008
 */

public class TypeSessionAttributeListener implements HttpSessionAttributeListener
{

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent)
	 */
	public void attributeAdded( HttpSessionBindingEvent event )
	{
		E885Logger.testLog.debug( "execute method attributeAdded()" );
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
	 */
	public void attributeRemoved( HttpSessionBindingEvent event )
	{
		E885Logger.testLog.debug( "execute method attributeRemoved()" );

		if( event.getName().equals( "MyBean" ) && event.getValue() instanceof MyBean )
		{
			if( isTimeout( event.getSession() ) )
				E885Logger.testLog.debug( "timeout, so MyBean is removed" );
			else
				E885Logger.testLog.debug( "MyBean is removed by calling the method session.removeAttribte()" );
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent)
	 */
	public void attributeReplaced( HttpSessionBindingEvent event )
	{
		E885Logger.testLog.debug( "execute method attributeReplaced()" );
	}

	/**
	 * check timeout<br>
	 * 
	 * @param session
	 * @return true, represents timeout
	 */
	private boolean isTimeout( HttpSession session )
	{
		try
		{
			long idleTime = new Date().getTime() - session.getLastAccessedTime();

			return idleTime >= session.getMaxInactiveInterval() * 1000;
		}
		catch( IllegalStateException ex )
		{
			//但是當 session 過期時, 容器也許會拒絕 getLastAccessedTime() 及 getMaxInactiveInterval() 方法被呼叫, 並會產生
			//java.lang.IllegalStateException.
			//所以當 catch IllegalStateException 時, 就是當做 session 過期了			
			return true;
		}
	}
}
